#include <cstdlib>
#include <iostream>
#include <memory>
using std::cout;
using std::endl;

template<typename T>
class Vector{
public:
    Vector()
    {
        _start = alloc.allocate(1);
        _finish = _start;
        _end_of_storage = _start + 1;
    }

    void push_back(const T & t){
        if(_finish == _end_of_storage){
            reallocate();
        }
        alloc.construct(_finish, t);
        ++_finish;
    }

    void pop_back(){
        if(size() == 0) return ;
        alloc.destroy(--_finish);
    } 

    size_t size(){
        return _finish - _start;
    }

    size_t capacity(){
        return _end_of_storage - _start;
    }

    ~Vector(){
        if(_start){
            std::destroy_n(_start,size());
            alloc.deallocate(_start,capacity());
        }
    }

private:
    static std::allocator<T> alloc;
    T * _start;
    T * _finish;
    T * _end_of_storage;
private:
    void reallocate(){ //动态扩容
        size_t old_size = size();
        size_t old_capacity = capacity();
        //申请新空间
        T * new_start = alloc.allocate(old_capacity * 2);
        //转移数据
        T * new_finish = std::uninitialized_copy(_start,_finish,new_start);
        //销毁旧数据，并释放内存
        std::destroy_n(_start,size());
        alloc.deallocate(_start,old_capacity);
        //更新指针
        _start = new_start;
        _finish = new_finish;
        _end_of_storage = _start +  2* old_capacity;
    }
};
template<typename T>
std::allocator<T> Vector<T>::alloc;

void test(){
    Vector<int> vec;
    cout <<"capacity:" << vec.capacity() << endl;
    cout <<"size:" << vec.size() << endl;
    vec.push_back(1);
    cout <<"capacity:" << vec.capacity() << endl;
    cout <<"size:" << vec.size() << endl;
    vec.push_back(2);
    vec.push_back(3);
    cout <<"capacity:" << vec.capacity() << endl;
    cout <<"size:" << vec.size() << endl;
    vec.push_back(4);
    vec.push_back(5);
    cout <<"capacity:" << vec.capacity() << endl;
    cout <<"size:" << vec.size() << endl;
}

int main()
{
    test ();
    return 0;
}

